package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private ClazzService clazzService;

    /**
     * 分页查询
     *
     * @param student 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<Student> getPageResult(StudentQueryParam student) {
        Page<Student> page = Page.of(student.getPage(), student.getPageSize());

        //根据最后时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));

        //构建查询条件(姓名，学历，班级)
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(student.getName() != null && !student.getName().isEmpty(), Student::getName, student.getName())
                .eq(student.getDegree() != null, Student::getDegree, student.getDegree())
                .eq(student.getClazzId() != null, Student::getClazzId, student.getClazzId());
        //调用page方法完成分页查询
        page = page(page,queryWrapper);

        //获取所有班级的班级名称的id
        List<Student> studentList = page.getRecords();

        if (!studentList.isEmpty()) {
            //批量查询这些班级名称的信息
            List<Integer> clazzIds = studentList.stream().map(Student::getClazzId).toList();

            //将班级名称封装到员工对象中
            studentList.forEach(student1 -> {
                clazzIds.forEach(clazzId -> {
                    if (student1.getClazzId() != null && student1.getClazzId().equals(clazzId)) {
                        Clazz clazz = clazzService.getByIdClazz(clazzId);
                        student1.setClazzName(clazz.getName());
                    }
                });
            });
        }

        //封装结果并返回
        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    /**
     * 保存学生信息
     *
     * @param student
     */
    @Override
    public void saveStudent(Student student) {

        //保存学员的基本信息
        student.setUpdateTime(LocalDateTime.now());
        save(student);
    }

    /**
     * 根据id查询学生信息
     *
     * @param id
     * @return
     */
    @Override
    public Student getByIdStudent(Integer id) {
        //根据id查询学员信息
        Student student = getById(id);

        //封装返回
        return student;
    }

    /**
     * 修改学生信息
     *
     * @param student
     */
    @Override
    public void updateStudent(Student student) {
        //调用service方法修改学员信息
        //根据id更新学员基本信息
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
    }


    /**
     * 根据id删除学生信息
     *
     * @param ids
     */
    @Override
    public void removeStudenntByIds(List<Integer> ids) {
        //调用service方法删除学员信息
        removeByIds(ids);
    }



    /**
     * 扣分
     *
     * @param id
     * @param score
     */
    @Override
    public void violation(Integer id, Integer score) {
        // 1. 参数校验
        if (id == null || score == null || score <= 0) {
            throw new IllegalArgumentException("参数不合法");
        }

        // 2. 原子性操作（使用MyBatis-Plus的lambdaUpdate）
        boolean updated = lambdaUpdate()
                .eq(Student::getId, id)
                .setSql("violation_score = violation_score + " + score)
                .setSql("violation_count = violation_count + 1")
                .update();

        // 3. 处理更新失败情况
        if (!updated) {
            throw new RuntimeException("学生不存在或更新失败");
        }
    }


}
